import { fileURLToPath, URL } from "node:url";
import * as fs from "node:fs/promises";
import * as path from "node:path";
import scriptUrl from "../src/components/framework/icon/scriptUrl";
import * as https from "https";

/* 下载字体图标脚本 */

// @ts-ignore
const __dirname = fileURLToPath(new URL(".", import.meta.url));

// 脚本路径源文件
const sourceOutFile = path.join(__dirname, "../src/components/framework/icon/scriptUrl.ts");
// 图标js文件输出目录
const publicDir = "static/icon";
const outDir = path.join(__dirname, `../public/${publicDir}`);

// 脚本输出文件名
const outputFileName = `iconfont.js`;
const outFilePath = path.join(outDir, outputFileName);
const publicFilePath = path.join(publicDir, outputFileName).replace(/\\/g, "/");

if (scriptUrl.startsWith("https://") || scriptUrl.startsWith("//")) {
  let url = scriptUrl;
  if (url.startsWith("//")) {
    url = `https:${url}`;
  }

  downloadFile(url)
    .then(async content => {
      await fs.mkdir(outDir, { recursive: true });
      await fs.writeFile(outFilePath, content, { encoding: "utf-8" });
      await fs.writeFile(sourceOutFile, sourceOutContent());

      console.log(`下载文件 ${scriptUrl} => ${publicFilePath}`);
    })
    .catch(e => {
      console.error(`文件下载失败 ${scriptUrl}`);
      console.error(e);
    });
}

function downloadFile(url: string): Promise<string> {
  return new Promise((resolve, reject) => {
    https.get(url, res => {
      res.setEncoding("utf-8");
      let data = "";
      res.on("data", chunk => {
        data += chunk;
      });

      res.on("end", () => resolve(data));
      res.on("error", e => reject(e));
    });
  });
}

function sourceOutContent() {
  return `const scriptUrl = "${publicFilePath}";
export default scriptUrl;
`;
}
